package weaver.interfaces.zhlx.duss.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import okhttp3.*;
import weaver.alioss.AliOSSObjectManager;
import weaver.alioss.AliOSSObjectUtil;
import weaver.common.DateUtil;
import weaver.conn.ConnStatement;
import weaver.conn.RecordSet;
import weaver.file.AESCoder;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.general.TimeUtil;
import weaver.general.Util;

import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipInputStream;

/**
 * @author dusongsong
 * @date 2023年08月23日 11:48
 */
public class SrmPMPUtil {

    private static  JSONObject propVal = PropUtil.getPropVal("zhlxsrmpmp");
    private static  String URL = propVal.getString("url");

    private static  Map<String, String> STRING_MAP = new HashMap();

    static {
        STRING_MAP.put("FundPlan", "/jeecg-boot/srm/oa/fundPlan");
        STRING_MAP.put("ProjFund", "/jeecg-boot/srm/oa/projFund");
        STRING_MAP.put("ProcessSpeed", "/jeecg-boot/srm/oa/processSpeed");
        STRING_MAP.put("ProjFundToRemainAmount", "/jeecg-boot/srm/oa/projFundToRemainAmount");
    }

    public static JSONObject sendOKHttpRequest(String apiType, String params) {
        JSONObject resultJson = new JSONObject();
        String code = "fail";
        String data = "";
        String message = "";
        String apiUrl = URL + Util.null2String(STRING_MAP.get(apiType));
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(60, TimeUnit.SECONDS)
                    .readTimeout(60, TimeUnit.SECONDS)
                    .writeTimeout(60, TimeUnit.SECONDS)
                    .build();
            MediaType mediaType = MediaType.parse("application/json");
            RequestBody body = RequestBody.create(mediaType, params);
            Request request = new Request.Builder()
                    .url(apiUrl)
                    .method("POST", body)
                    .addHeader("Content-Type", "application/json")
                    .build();
            Response response = client.newCall(request).execute();
            String result = Util.null2String(response.body().string());
            if (!"".equals(result)) {
                data = result;
                code = "success";
            } else {
                message = "response result is null";
            }
        } catch (Exception e) {
            message = "response timeout";
            e.printStackTrace();
        }
        resultJson.put("code", code);
        resultJson.put("data", data);
        resultJson.put("message", message);
        return resultJson;
    }

    /**
     * 付款信息推送接口
     *
     * @param content
     * @return
     */
    public static JSONObject fundPlan(JSONObject content, Map<String, Object> dataMap) {
        JSONObject resultJson = sendOKHttpRequest("FundPlan", content.toJSONString());
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, "FundPlan");
        return resultJson;
    }

    /**
     * 付款信息推送接口
     *
     * @param content
     * @return
     */
    public static JSONObject projFund(JSONObject content, Map<String, Object> dataMap) {
        JSONObject resultJson = sendOKHttpRequest("ProjFund", content.toJSONString());
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, "ProjFund");
        return resultJson;
    }

    /**
     * 节点信息推送接口
     *
     * @param content
     * @return
     */
    public static JSONObject processSpeed(JSONObject content, Map<String, Object> dataMap) {
        JSONObject resultJson = sendOKHttpRequest("ProcessSpeed", content.toJSONString());
        if (content.containsKey("attachment")) {
            content.put("attachment", "");
        }
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, "ProcessSpeed");
        return resultJson;
    }

    /**
     * 未清凭证推送接口
     *
     * @param content
     * @return
     */
    public static JSONObject projFundToRemainAmount(JSONObject content, Map<String, Object> dataMap) {
        JSONObject resultJson = sendOKHttpRequest("ProjFundToRemainAmount", content.toJSONString());
        dataMap.put("jkqqcs", content);
        dataMap.put("jkxycs", resultJson);
        insertApiLog(dataMap, "ProjFundToRemainAmount");
        return resultJson;
    }

    //根据表单和字段获取下拉框值
    public static String getSelectname(int billid, String fieldname, String selectvalue) {
        RecordSet rs = new RecordSet();
        String sql = "select t1.selectvalue,t1.selectname from workflow_selectitem t1 left join workflow_billfield t2\n" +
                " on t1.fieldid=t2.id where abs(t2.billid)=? and t2.fieldname=? and t1.selectvalue=?";
        rs.executeQuery(sql, billid, fieldname, selectvalue);
        rs.next();
        return Util.null2String(rs.getString("selectname"));
    }

    /**
     * 获取节点名称
     */
    public static JSONObject getNodebaseNodename(int nodeid) {
        RecordSet rs = new RecordSet();
        JSONObject json = new JSONObject();
        rs.executeQuery("select isstart,nodename,isend from workflow_nodebase where id=?", nodeid);
        rs.next();
        json.put("isstart", Util.null2String(rs.getString("isstart")));
        json.put("nodename", Util.null2String(rs.getString("nodename")));
        json.put("isend", Util.null2String(rs.getString("isend")));
        return json;
    }

    /**
     * 获取签字意见附件信息
     */
    public static JSONArray getImageFile(String docids) {
        BaseBean baseBean = new BaseBean();
        RecordSet rs = new RecordSet();
        JSONArray fileList = new JSONArray();
        baseBean.writeLog(">>>>>getImageFile>>>>>docids=" + docids);
        rs.executeQuery("select imagefileid,imagefilename from DocImageFile where docid in (" + docids + ")");
        while (rs.next()) {
            JSONObject dataJson = new JSONObject();
            int imagefileid = Util.getIntValue(rs.getString("imagefileid"), -1);
            String imagefilename = Util.null2String(rs.getString("imagefilename"));
            dataJson.put("name", imagefilename);
            baseBean.writeLog(">>>>imagefileid=" + imagefileid);
            baseBean.writeLog(">>>>imagefilename=" + imagefilename);
            try {
                InputStream inputStream = getInputStreamById(imagefileid);
                ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024 * 100];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    byteArrayOutputStream.write(buffer, 0, bytesRead);
                }
                byteArrayOutputStream.flush();
                dataJson.put("value", byteArrayOutputStream.toByteArray());
            } catch (Exception e) {
                e.printStackTrace();
            }
            fileList.add(dataJson);
        }
        return fileList;
    }

    /**
     * 返回文件流   已经经过脱密、解压
     *
     * @param imageFileId_para
     * @return 文件流
     * @throws Exception
     */
    public static InputStream getInputStreamById(int imageFileId_para) {
        InputStream imagefile = null;
        try {
            RecordSet rs = new RecordSet();
            String sql = "select fileRealPath,isZip,isaesencrypt,aescode,tokenKey,storageStatus  from ImageFile where imageFileId = " + imageFileId_para;
            rs.executeQuery(sql);
            if (rs.next()) {
                String static_fileRealPath = Util.null2String(rs.getString("fileRealPath"));
                String static_isZip = Util.null2String(rs.getString("isZip"));
                int static_isaesencrypt = Util.getIntValue(rs.getString("isaesencrypt"), 0);
                String static_aescode = Util.null2String(rs.getString("aescode"));
                String static_tokenKey = Util.null2String(rs.getString("tokenKey"));
                String static_storageStatus = Util.null2String(rs.getString("storageStatus"));
                boolean isonlyAliOSS = false;
                if (!static_tokenKey.equals("") && static_storageStatus.equals("1") && AliOSSObjectManager.isonlyAliOSS()) {
                    isonlyAliOSS = true;
                }
                if (isonlyAliOSS) {
                    imagefile = AliOSSObjectUtil.downloadFile(static_tokenKey);
                } else {
                    if (static_fileRealPath != null && !static_fileRealPath.equals("")) {
                        File thefile = new File(static_fileRealPath);
                        if (static_isZip.equals("1")) {
                            ZipInputStream zin = new ZipInputStream(new FileInputStream(thefile));
                            if (zin.getNextEntry() != null) {
                                imagefile = new BufferedInputStream(zin);
                            }
                        } else {
                            imagefile = new BufferedInputStream(new FileInputStream(thefile));
                        }
                    } else {
                        ConnStatement statement = null;
                        try {
                            statement = new ConnStatement();
                            boolean isoracle = ("oracle").equals(statement.getDBType());
                            statement.setStatementSql("select imagefile from ImageFile where imagefileid = " + imageFileId_para);
                            statement.executeQuery();
                            if (statement.next()) {
                                if (isoracle) {
                                    imagefile = new BufferedInputStream(statement.getBlobBinary("imagefile"));
                                } else {
                                    imagefile = new BufferedInputStream(statement.getBinaryStream("imagefile"));
                                }
                            }
                        } catch (Exception ex) {
                        } finally {
                            try {
                                if (statement != null) {
                                    statement.close();
                                }
                            } catch (Exception ex) {
                            }
                        }
                    }
                    if (static_isaesencrypt == 1) {
                        imagefile = AESCoder.decrypt(imagefile, static_aescode);
                    }

                }
            }


        } catch (Exception ex) {

        }
        return imagefile;
    }


    /**
     * 插入接口日志
     *
     * @param dataMap
     * @param apiType
     */
    public static void insertApiLog(Map<String, Object> dataMap, String apiType) {
        String apiUrl = URL + Util.null2String(STRING_MAP.get(apiType));
        String fullDate = DateUtil.getFullDate();
        try {
            InetAddress address = InetAddress.getLocalHost();
            String serverIp = address.getHostAddress();
            dataMap.put("fwqdz", serverIp);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        dataMap.put("jkqqdz", apiUrl);
        dataMap.put("jkdysj", fullDate);
        dataMap.put("jktgf", "(SRM)项目管理平台");
        insertModelData("uf_apilog", 1, dataMap);
    }

    //建模权限重构
    public static void newModeRight(int userid, int formmodeid, int id) {
        ModeRightInfo modeRightInfo = new ModeRightInfo();
        modeRightInfo.setNewRight(true);
        modeRightInfo.editModeDataShare(userid, formmodeid, id);
    }

    //将数据插入表单建模
    public static int insertModelData(String tablename, int userid, Map<String, Object> map) {
        int dataid = 0;
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        //查询该模块表名
        try {
            String sql = "select a.id from modeinfo a left join workflow_bill b on a.formid=b.id where b.tablename=?";
            rs.executeQuery(sql, tablename);
            rs.next();
            int modeid = Util.getIntValue(rs.getString("id"));
            String uuid = UUID.randomUUID().toString();
            String insSql = "insert into " + tablename
                    + "(modeuuid,modedatacreater,modedatacreatedate,modedatacreatetime,formmodeid)values(?,?,?,?,?)";
            Object[] params = {uuid, userid, TimeUtil.getCurrentDateString(), TimeUtil.getOnlyCurrentTimeString(), modeid};
            if (rs.executeUpdate(insSql, params)) {
                rs1.executeQuery("select id from " + tablename + " where modeuuid=?", uuid);
                rs1.next();
                dataid = Util.getIntValue(rs1.getString("id"));
                if (dataid > 0) {
                    //遍历数据 进行update
                    String updatesql = "update " + tablename + " set ";
                    Set<String> keySet = map.keySet();
                    for (String key : keySet) {
                        updatesql += key + "='" + map.get(key).toString() + "',";
                    }
                    if (updatesql.endsWith(",")) {
                        updatesql = updatesql.substring(0, updatesql.length() - 1);
                        updatesql += " where id=" + dataid;
                        rs.executeUpdate(updatesql);
                    }
                    //进行权限重构
                    newModeRight(userid, modeid, dataid);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return dataid;
    }


}
